package pl.register.android.activities.tasks;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
import pl.register.android.R;
import pl.register.android.activities.tasks.builders.DeleteTaskConfirmationDialogBuilder;
import pl.register.android.activities.tasks.ui.TasksListAdapter;
import pl.register.android.database.DatabaseAdapter;
import pl.register.android.database.dao.TaskDao;
import pl.register.android.task.Task;
import pl.register.android.util.ListItemMode;

import java.util.List;

/**
 * @author Mateusz Strzelecki
 * @since 2013-05-02
 */
public class TasksListFragment extends SherlockFragment
        implements AdapterView.OnItemClickListener {

    private ListView lvTasks;

    private TasksListAdapter listAdapter;

    private DatabaseAdapter databaseAdapter;

    private OnItemSelectedListener listener;

    private TaskDao taskDao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentLayout = inflater.inflate(R.layout.tasks_list_fragment_layout, container, false);
        databaseAdapter = new DatabaseAdapter(getActivity());
        databaseAdapter.open();
        taskDao = databaseAdapter.getTaskDao();

        registerViews(contentLayout);
        setupContent();
        populateList();
        return contentLayout;
    }

    private void registerViews(View content) {
        lvTasks = (ListView) content.findViewById(R.id.tasks_list_view);
    }

    private void setupContent() {
        listAdapter = new TasksListAdapter(getActivity(), this);
        lvTasks.setAdapter(listAdapter);
        lvTasks.setOnItemClickListener(this);
        registerForContextMenu(lvTasks);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString() + " must implemenet MyListFragment.OnItemSelectedListener");
        }
    }

    private void populateList() {
        List<Task> tasks = taskDao.getTasks();
        listAdapter.refreshItems(tasks);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.context_menu_task, menu);
        menu.setHeaderTitle("Wybierz opcję");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        Task clickedTask = listAdapter.getItem(position);
        switch (item.getItemId()) {
            case R.id.menu_task_show:
                listener.onTaskItemSelected(clickedTask);
                return true;
            case R.id.menu_task_edit:
                listener.onTaskEditing(clickedTask);
                return true;
            case R.id.menu_task_delete:
                showDeleteTaskConfirmationDialog(clickedTask);
                return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Task clickedTask = listAdapter.getItem(position);
        listener.onTaskItemSelected(clickedTask);
    }

    public void showDeleteTaskConfirmationDialog(final Task taskToRemove) {
        AlertDialog.Builder dialogConfirmation = new DeleteTaskConfirmationDialogBuilder(getActivity(), taskToRemove);
        dialogConfirmation.setNegativeButton(R.string.btn_name_no, null);
        dialogConfirmation.setPositiveButton(R.string.btn_name_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                taskDao.delete(taskToRemove);
                removeTask(taskToRemove);
                listener.onTaskRemoved(taskToRemove);
            }
        });
        dialogConfirmation.create().show();
    }

    public void saveTask(Task task) {
        taskDao.save(task);
        listAdapter.refresh();
    }

    public void addTask(Task task) {
        listAdapter.add(task);
    }

    public void removeTask(Task task) {
        listAdapter.remove(task);
    }

    public void showDeleteBtn() {
        listAdapter.changeItemsMode(ListItemMode.DELETE);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listener = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseAdapter != null) {
            databaseAdapter.close();
        }
    }

    public interface OnItemSelectedListener {

        public void onTaskItemSelected(Task task);

        public void onTaskEditing(Task task);

        public void onTaskRemoved(Task task);

    }
}